import * as React from "react";
import { Provider } from "react-redux";
import { applyMiddleware, combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import { createLogger } from "redux-logger";
import { combineEpics, createEpicMiddleware } from "redux-observable";

import { App } from "./app";

import * as fromAggRole from "./pages/admin/containers/agg-role/reducer";

export interface RootStoreState {
  [fromAggRole.NAME]: fromAggRole.StoreState;
}

const rootEpic = combineEpics(...fromAggRole.epics);

const epicMiddleware = createEpicMiddleware();

const rootReducer = combineReducers<RootStoreState>({
  [fromAggRole.NAME]: fromAggRole.reducer
});

const composeEnhancers = composeWithDevTools({
  actionSanitizer: actionTransformer
});

const ActTypes = [fromAggRole.ActTypes];

const logger = createLogger({
  actionTransformer
});

const rootStore = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(epicMiddleware, logger))
);

epicMiddleware.run(rootEpic);

export const AppWithProvider = () => (
  <Provider store={rootStore}>
    <App />
  </Provider>
);

function actionTransformer(action) {
  for (const v of ActTypes) {
    const type = v[action.type];
    if (type) {
      return {
        ...action,
        type
      };
    }
  }
  return action;
}
